<?php
App::uses('AppController', 'Controller');
App::uses('Sanitize', 'Utility');
/**
 * Applications Controller
 *
 * @property Application $Application
 */
class ApplicationsController extends AppController {

	public $helpers = array('Date', 'Datefr', 'Moninput', 'Session_gpp');
/**
*RLEB
*Definition d'un pagination a 25 appli/page + tri par defaut sur Application.name
*/
	/*public $paginate = array(
        'limit' => 25,
        'order' => array(
            'Application.name' => 'asc'
        )
    );*/

/**
*RLEB
*Helper Date pour transformer la date au formmat lundi 10 mai 2012
*/
    //public $helpersfr = array('Datefr');

	/*function beforeFilter(){
		parent::beforeFilter();
		//$this->Auth->allow('index');
	}*/
/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Application->recursive = -1;
		$data = $this->paginate('Application');

		foreach ($data as $application):
			$nbversion = $this->Application->Version->find('count', array(      'fields' => 'Version.id',      'conditions' => array('Version.application_id =' => $application['Application']['id']) ,'recursive'=>-1  ));
			$nbversions[$application['Application']['id']]=array("count"=>$nbversion);
		endforeach;

		if (isset($nbversions)){
			$this->set('nbversions', $nbversions);
		}
		$this->set('applications', $data);
	}

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($app_id = null) {
		$app_id = Sanitize::paranoid($app_id);
		$app_id = Sanitize::clean($app_id, array('encode' => false, 'unicode'=> true));

		$this->Application->id = $app_id;
		if (!$this->Application->exists()) {
			throw new NotFoundException(__('Invalid application'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data=Sanitize::clean($this->request->data, array('encode' => false, 'unicode'=> true));
			if ($this->Application->save($this->request->data)) {;
				$this->Session->setFlash( __('The application has been saved'),'default',array("class"=>'success'));
				$this->redirect(array('action' => 'view',$app_id));
			} else {
				$this->Session->setFlash( __('The application could not be saved. Please, try again.'),'default',array("class"=>'error'));
			}
		} else {
			$pgdatabases = $this->Application->Pgdatabase->find('list');
			$this->set(compact('pgdatabases'));
			$this->request->data = $this->Application->read(null, $app_id);
		}
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($app_id = null) {
		$app_id = Sanitize::paranoid($app_id);
		$app_id = Sanitize::clean($app_id, array('encode' => false, 'unicode'=> true));

		$this->Application->id = $app_id;
		if (!$this->Application->exists()) {
			throw new NotFoundException(__('Invalid application'));
		}
		$pgdatabases = $this->Application->Pgdatabase->find('list');
		$this->set(compact('pgdatabases'));
		$this->set('application', $this->Application->read(null, $app_id));
	}

/**
 * add method
 *
 * @return void
 */

	public function add() {
		if ($this->request->is('post')) {
			$this->request->data=Sanitize::clean($this->request->data, array('encode' => false, 'unicode'=> true));
			$this->Application->create();
			if ($this->Application->save($this->request->data)) {
				try {
					if($this->request->data['Application']['hebergement']=='0'){
						$this->Application->query('CREATE DATABASE `Gestparamphp_$'.$this->Application->id.'` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;');
					} 
					$this->Session->setFlash( __('The application has been saved'),'default',array("class"=>'success'));
					$this->redirect(array('action' => 'index'));
				} catch (Exception $e) {
					$this->Application->delete();
					$this->Session->setFlash( __('The application could not be saved. Contact your administrator.'),'default',array("class"=>'error'));
					$this->Application->delete();
				}
			} else {
				$this->Session->setFlash( __('The application could not be saved. Please, try again.'),'default',array("class"=>'error'));
			}
		}
		$pgdatabases = $this->Application->Pgdatabase->find('list');
		$this->set(compact('pgdatabases'));
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$id = Sanitize::paranoid($id);
		$id = Sanitize::clean($id, array('encode' => false, 'unicode'=> true));

		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Application->id = $id;
		if (!$this->Application->exists()) {
			throw new NotFoundException(__('Invalid application'));
		}

		$appli = $this->Application->find('first',array('conditions' => array('Application.id' => $id),'recursive'=>-1));
		
		if ($this->Application->delete()) {
        	try {
				if($appli['Application']['hebergement']=='0'){
        			$this->Application->query('DROP DATABASE `Gestparamphp_$'.$id.'`;');
        		}
				$this->Session->setFlash( __('The application has been deleted'),'default',array("class"=>'success'));
				$this->redirect(array('action' => 'index'));
			} catch (Exception $e) {
				$this->Session->setFlash( __('The application could not be deleted. Contact your administrator.'),'default',array("class"=>'error'));
			}
		}
		$this->Session->setFlash( __('The application could not be deleted. Please, try again.'),'default',array("class"=>'error'));
		$this->redirect(array('action' => 'index'));
	}


	public function TesterConnexion_ajax($ApplicationPgdatabase='', $ApplicationHost='', $ApplicationPort='', $ApplicationSid='', $ApplicationLogin='', $ApplicationMdp='', $encoding='', $unixsocket='') {
		$this->layout = 'ajax';

		$ApplicationPgdatabase = Sanitize::paranoid($ApplicationPgdatabase);
		$appli['pgdatabase_id'] = Sanitize::clean($ApplicationPgdatabase, array('encode' => false, 'unicode'=> true));
		$appli['host'] = Sanitize::clean($ApplicationHost, array('encode' => false, 'unicode'=> true));
		$ApplicationPort = Sanitize::paranoid($ApplicationPort);
		$appli['port'] = Sanitize::clean($ApplicationPort, array('encode' => false, 'unicode'=> true));
		$ApplicationSid = Sanitize::paranoid($ApplicationSid);
		$appli['sid'] = Sanitize::clean($ApplicationSid, array('encode' => false, 'unicode'=> true));
		$appli['login'] = Sanitize::clean($ApplicationLogin, array('encode' => false, 'unicode'=> true));
		$appli['mdp'] = Sanitize::clean($ApplicationMdp, array('encode' => false, 'unicode'=> true));
		$appli['encoding'] = Sanitize::clean($encoding, array('encode' => false, 'unicode'=> true));
		$appli['unixsocket'] = Sanitize::clean($unixsocket, array('encode' => false, 'unicode'=> true));

		try{
			$MyConnection =& $this->Maconnexion->connect($appli, 1);
			echo "Connexion successfull";
			exit();
		}catch(Exception $e){
		    echo ($e->getMessage());
		    exit();
		}

		echo "Pb Lors du test. Veuiller contacter votre Administrateur";
		
	}
}
